'use strict';

/* Controllers */

angular.module('app')
    .controller('AppCtrl', ['$scope', '$q', '$rootScope', '$translate', '$localStorage', '$window', '$http', '$state', 'dialogs', '$sessionStorage', 'UserInfo', 'Dictionary',
        function ($scope, $q, $rootScope, $translate, $localStorage, $window, $http, $state, dialogs, $sessionStorage, UserInfo, Dictionary) {
            // add 'ie' classes to html
            var isIE = !!navigator.userAgent.match(/MSIE/i);
            isIE && angular.element($window.document.body).addClass('ie');
            isSmartDevice($window) && angular.element($window.document.body).addClass('smart');

            // config
            $scope.app = {
                name: '综合信息管理',
                version: '1.4.7',
                jsVersion : '0.0.1',
                // for chart colors
                color: {
                    primary: '#7266ba',
                    info: '#23b7e5',
                    success: '#27c24c',
                    warning: '#fad733',
                    danger: '#f05050',
                    light: '#e8eff0',
                    dark: '#3a3f51',
                    black: '#1c2b36'
                },
                settings: {
                    themeID: 8,
                    navbarHeaderColor: 'bg-info dker',
                    navbarCollapseColor: 'bg-info dker',
                    asideColor: 'bg-light dker b-r',
                    headerFixed: true,
                    asideFixed: false,
                    asideFolded: false,
                    asideDock: false,
                    container: false
                }
            }
            
            top.window.jsVersion = $scope.app.jsVersion;
            
            // save settings to local storage
            if (angular.isDefined($localStorage.settings)) {
                $scope.app.settings = $localStorage.settings;
            } else {
                $localStorage.settings = $scope.app.settings;
            }
            $scope.$watch('app.settings', function () {
                if ($scope.app.settings.asideDock && $scope.app.settings.asideFixed) {
                    // aside dock and fixed must set the header fixed.
                    $scope.app.settings.headerFixed = true;
                }
                // save to local storage
                $localStorage.settings = $scope.app.settings;
            }, true);

            // angular translate
            $scope.lang = {isopen: false, center_line_name: 'zh-CN', name: 'zh-CN'};
            $scope.langs = {zh_CN: '中文', en: 'English'};
            $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "中文";
            $scope.setLang = function (langKey, $event) {
                // set the current lang
                $scope.selectLang = $scope.langs[langKey];
                $scope.lang.center_line_name = langKey.replace('_', '-');
                $scope.lang.name = langKey;
                // You can change the language during runtime
                $translate.use(langKey);
                $scope.lang.isopen = !$scope.lang.isopen;
            };

            function isSmartDevice($window) {
                // Adapted from http://www.detectmobilebrowsers.com
                var ua = $window['navigator']['userAgent'] || $window['navigator']['module'] || $window['opera'];
                // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
                return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
            }

            // 读取用户权限
            $rootScope.hasPermission = UserInfo.isAuthorized;
            $rootScope.hasGroup = UserInfo.hasGroup;
            $rootScope.hasAuth = UserInfo.hasAuth;

            // 刷新用户权限信息
            $rootScope.flushUserInfo = function(){
                var deferred = $q.defer();
                UserInfo.flush().then(function () {
                    $rootScope.main = UserInfo.getEntity();
                    $rootScope.authorities = UserInfo.getAuthorities();
                    deferred.resolve($rootScope.main);
                });
                return deferred.promise;
            };
            // 获取用户信息不刷新
            $rootScope.getUserInfo = function(){
            	var deferred = $q.defer();
            	UserInfo.get().then(function () {
            		$rootScope.main = UserInfo.getEntity();
            		$rootScope.authorities = UserInfo.getAuthorities();
            		deferred.resolve($rootScope.main);
            	});
            	return deferred.promise;
            };
            $rootScope.cleanUserInfo = function(){
                UserInfo.cleanUserInfo();
            };
            if(!UserInfo.isAuthenticated()) {
                $rootScope.getUserInfo();
            }



            // 装载数据字典
            Dictionary.load();

            $scope.openChanagePwd = function () {
                dialogs.create('tpl\/blocks\/changePWD.html', 'changePWDCtrl', null, {
                    size: 'md',
                    keyboard: true,
                    backdrop: true,
                    windowClass: 'my-class'
                });
            }

//      $rootScope.login = function(){
//        dialogs.create('tpl-system\/login.html','loginFormController',null,{size:'md',keyboard: true,backdrop: true,windowClass: 'my-class'});
//      }
            $rootScope.loginout = function () {
                $http.get('j_spring_security_logout').success(function (res) {
                    if (res.success) {
                        $rootScope.cleanUserInfo();
                        $rootScope.flushUserInfo();
                        $state.go('access.login');
                    }
                });

            }

        }]);

app.controller('changePWDCtrl', ['$scope', '$uibModalInstance', 'data', 'httpWrapService', 'dialogs', function ($scope, $uibModalInstance, data, httpWrapService, dialogs) {
    $scope.data = {};


    $scope.cancel = function () {
        $uibModalInstance.dismiss('Canceled');
    }; // end cancel

    $scope.ok = function () {
        httpWrapService.post('changePWD.do', {
            password: $scope.password
        }).then(function () {
            $uibModalInstance.close();
            dialogs.notify('信息', '修改成功', {size: 'sm'});
        }, function () {
            dialogs.notify('错误', '修改失败', {size: 'sm'});
        });

    };

}]); // end controller(customDialogCtrl)